#include <QApplication>
#include <QDateTime>
#include <QDebug>


#include <QProcess>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>

// QString generateMarkdown(const QString& jsonStr) {
//     QJsonDocument doc = QJsonDocument::fromJson(jsonStr.toUtf8());
//     QJsonObject manifest = doc.object();
    
//     QString output = "# Repo Manifest Structure\n\n";
    
//     // 解析远程仓库
//     output += "## Remote Repositories\n";
//     QJsonArray remotes = manifest["remotes"].toArray();
//     for (auto&& r : remotes) {
//         QJsonObject remote = r.toObject();
//         output += QString("- `%1`: %2\n").arg(remote["name"].toString(), remote["fetch"].toString());
//     }
    
//     // 解析项目结构
//     output += "\n## Project Structure\n```\n";
//     QJsonArray projects = manifest["projects"].toArray();
//     for (auto&& p : projects) {
//         QJsonObject project = p.toObject();
//         output += QString("%1\n").arg(project["path"].toString());
//     }
//     output += "```\n";
    
//     return output;
// }

// Bug..
// QString generateMarkdown(const QJsonArray& projects) {
//     QMap<QString, QMap<QString, QSet<QString>>> structure;
    
//     // 构建目录树
//     for (auto&& p : projects) {
//         QJsonObject project = p.toObject();
//         QString path = project["path"].toString();
        
//         // 拆分路径层级
//         QStringList parts = path.split('/');
//         if (parts.isEmpty()) continue;
        
//         QString rootDir = parts[0];
//         if (rootDir == "development") {
//             if (parts.size() > 1) {
//                 QString subDir = parts[1];
//                 QString item = parts.size() > 2 ? parts[2] : project["name"].toString();
//                 structure["development"][subDir].insert(item);
//             }
//         } 
//         else if (rootDir.startsWith("linux-")) {
//             QString item = parts.size() > 1 ? parts[1] : project["name"].toString();
//             structure[rootDir][""].insert(item);
//         }
//         else if (rootDir == "build-scripts") {
//             structure["build-scripts"][""].insert("");
//         }
//     }

//     // 生成Markdown
//     QString output = "```\n";
//     for (auto it = structure.begin(); it != structure.end(); ++it) {
//         output += it.key() + "\n";
//         const auto& subDirs = it.value();
        
//         for (auto subIt = subDirs.begin(); subIt != subDirs.end(); ) {
//             QString prefix = (subIt == subDirs.begin()) ? "├── " : "└── ";
//             if (!subIt.key().isEmpty()) {
//                 output += "│   " + prefix + subIt.key() + "\n";
//                 const auto& items = subIt.value();
//                 for (auto itemIt = items.begin(); itemIt != items.end(); ) {
//                     QString itemPrefix = (++itemIt == items.end()) ? "    └── " : "    ├── ";
//                     output += "│   " + itemPrefix + *itemIt + "\n";
//                 }
//             } else {
//                 for (auto itemIt = subIt.value().begin(); itemIt != subIt.value().end(); ++itemIt) {
//                     output += "├── " + *itemIt + "\n";
//                 }
//             }
//             ++subIt;
//         }
//     }
//     output += "```";
//     return output;
// }

QString generateMarkdown(const QJsonArray& projects) {
    struct DirNode {
        QMap<QString, DirNode> children;
        bool hasProject = false;
    };
    DirNode root;

    // 构建目录树
    for (const auto& p : projects) {
        QJsonObject project = p.toObject();
        QString path = project["path"].toString();
        
        // 特殊标记构建脚本
        if (project.contains("linkfile")) {
            path += " (with linkfile)";
        }

        QStringList parts = path.split('/');
        DirNode* current = &root;
        
        for (const QString& part : parts) {
            if (!current->children.contains(part)) {
                current->children[part] = DirNode();
            }
            current = &current->children[part];
        }
        current->hasProject = true;
    }

    // 递归生成树形结构
    QStringList lines;
    std::function<void(const DirNode&, QString, QString)> traverse;
    
    traverse = [&](const DirNode& node, QString prefix, QString indent) {
        const int count = node.children.size();
        int index = 0;
        
        for (auto it = node.children.begin(); it != node.children.end(); ++it, ++index) {
            bool isLast = (index == count - 1);
            QString connector = isLast ? "└── " : "├── ";
            
            lines << prefix + connector + it.key();
            
            if (!it->children.isEmpty() || it->hasProject) {
                QString newPrefix = indent + (isLast ? "    " : "│   ");
                traverse(*it, newPrefix, newPrefix);
            }
        }
    };

    traverse(root, "", "");
    return "```\n" + lines.join("\n") + "\n```";
}

void test_dir_node(const QJsonArray &projects) {
    struct DirNode {
        QMap<QString, DirNode> children;
        bool hasProject = false;
    };
    DirNode root;

    qDebug() << projects;

    // 构建目录树
    for (const auto& p : projects) {
        QJsonObject project = p.toObject();
        QString path = project["path"].toString();

        // 特殊标记构建脚本
        if (project.contains("linkfile")) {
            path += " (with linkfile)";
        }

        QStringList parts = path.split('/');
        DirNode* current = &root;

        for (const QString& part : parts) {
            if (!current->children.contains(part)) {
                current->children[part] = DirNode();
            }
            current = &current->children[part];
        }
        current->hasProject = true;

        qDebug().noquote() << path;
    }
}

QString repo_manifest_json_str() {
    // 执行命令
    QProcess proc;
#ifdef QT_DEBUG
    char* repo = getenv("DEBUG_REPO");
    proc.setWorkingDirectory(repo);
#endif
    proc.start("repo manifest --json");
    proc.waitForFinished();
    return proc.readAllStandardOutput();
}

QJsonObject repo_manifest_json_object() {
    QJsonDocument doc = QJsonDocument::fromJson(repo_manifest_json_str().toUtf8());
    return doc.object();
}

QJsonArray repo_manifest_project_array() {
    return repo_manifest_json_object().value("project").toArray();
}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    test_dir_node(repo_manifest_project_array());

    // 生成文档
    QString markdown = generateMarkdown(repo_manifest_project_array());
    qDebug().noquote() << markdown;

    return 0;
}
